import Cookies from 'js-cookie'
import Config from './config.js'
import { dateUtils } from '@/common/util';
import {mapState,mapMutations} from 'vuex'

const TokenKey = 'vue_cut_app_token'
const IsUseCookies = false;

// 获取UTC时间
function getUTCTime(now) {
  let year = now.getUTCFullYear();
  let month = now.getUTCMonth();
  let date = now.getUTCDate();
  let hours = now.getUTCHours();
  let minutes = now.getMinutes();
  let seconds = now.getUTCSeconds();
  let ms = now.getUTCMilliseconds();
  return Date.UTC(year, month, date, hours, minutes, seconds, ms);
}
 function isTokenExpire(serverTokenExpire) {
	var ret = getUTCTime(new Date()) >= getUTCTime(new Date(serverTokenExpire));
	return ret;
}

export function getToken() {
	if(IsUseCookies){
		var data = Cookies.get(TokenKey);
		try{
		  var arr = JSON.parse(data);
		}catch(e){
		  return data;
		}
		return arr.token;
	}else{
		var data = uni.getStorageSync(TokenKey);
		// console.log(data)
		// try{
		//   var arr = JSON.parse(data);
		// }catch(e){
		//   return data;
		// }
		return data.token;
	}
}

export function setToken(data, expires_day) {
	if(IsUseCookies){
		if(expires_day){
			return Cookies.set(TokenKey, data, { expires: expires_day });
		}
		return Cookies.set(TokenKey, data);
	}else{
		uni.setStorageSync(TokenKey,  data )
	}
}

export function removeToken() {
	if(IsUseCookies){
		return Cookies.remove(TokenKey)
	}else{
		try {
		    uni.removeStorageSync(TokenKey);
		} catch (e) {
		    // error
		}
	}
}

export async function refreshToken() {
	var option = {
		url : Config.url['auth.refresh'],
		method : 'PUT',
	};
	option.header = {
		'Content-Type':'application/x-www-form-urlencoded',
	}
	
	try{
		if(IsUseCookies){
			var data = Cookies.get(TokenKey);
			var arr = JSON.parse(data);
		}else{
			var arr = uni.getStorageSync(TokenKey);
		}
		
		var oldToken = arr.token;
		if(oldToken && !isTokenExpire(arr.expired_at)){
			console.log('expired_at 未过期 不需要刷新 '+arr.expired_at);
			return false;
		}
		if(isTokenExpire(arr.refresh_expired_at)){
			console.log('refresh_expired_at 过期 '+arr.refresh_expired_at);
			//需要重登录
			removeToken();
			return false;
		}
		console.log('开始刷新token');
	}catch(e){
		console.log('cookie 数据 过期 ');
		return false;
	}
	// console.log('oldToken : ', oldToken)
	if(oldToken && oldToken != 'undefined'){
		option.header['Authorization'] = 'Bearer ' + oldToken;
	}else{
		return false;
	}
	// option.success = function(res){
	// 	if(res.statusCode && res.statusCode >= 400){
	// 		if(Config.show_err){
	// 			uni.showModal({
	// 				title: '异常', 
	// 				content: ''+res.data.message,
	// 				showCancel: false
	// 			});
	// 		}
	// 		if(res.statusCode == 401 && res.message == 'Token has expired'){
	// 			//跳转登录页面
	// 		}
			
	// 	}
	// }
	// option.fail = function(err){
	// 	console.log('err: ', err);
	// }
	
	var [error, res] = await  uni.request(option);
	if(error){
		console.log('error : '+error);
		return false;
	}
	console.log('refreshToken return ', res)
	if(res.statusCode == 200){
		var tokenInfo = res.data.data;
		console.log('refreshToken '+tokenInfo.token, tokenInfo);
		setToken(tokenInfo);
		return tokenInfo.token;
	}
	
	return false;
}